/*
 * @Author: 2112778581 2112778581@qq.com
 * @Date: 2024-01-02 14:42:07
 * @LastEditors: 2112778581 2112778581@qq.com
 * @LastEditTime: 2024-01-02 14:42:08
 * @FilePath: \my-sjksh\canvas\app.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// hierarchy 等级制度的意思
const dataSource = 'https://s5.ssl.qhres2.com/static/b0695e2dd30daa64.json';

(async function (){
    const data = await (await fetch(dataSource)).json()

    const regions = d3.hierarchy(data)
        .sum(d => 1)
        .sort((a,b) => b.value - a.value)
    // console.log('data', regions);

    const pack = d3.pack()
        .size([1600,1600])
        .padding(3)
    const canvas = document.querySelector('canvas')
    const context = canvas.getContext('2d')
    const root = pack(regions)

    const TAU = 2 * Math.PI

    function draw(ctx, node, { fillStyle = 'rgba(0,0,0,0.2)', textColor = 'white'} = {}) {
        const children = node.children
        const { x, y ,r } = node
        ctx.fillStyle = fillStyle
        ctx.beginPath()
        ctx.arc(x,y,r,0,TAU)
        ctx.fill()
        if (children) {
            for(let i = 0;i < children.length;i++) {
                draw(context, children[i])
            }
        } else {
            const name = node.data.name
            ctx.fillStyle = textColor
            ctx.font = '1.5rem Arial'
            ctx.textAlign = 'center'
            ctx.fillText(name, x, y)
        }
    }
    draw(context, root)
    // console.log('root', root);
}())